package com.yjd.back.contentmanager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.IntroDetailModel;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.base.service.IIntroDetailService;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.fundservice.dto.FundChannelDto;
import com.yjd.comm.fundservice.model.FundChannelModel;
import com.yjd.comm.fundservice.service.IFundChannelService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.tag.service.ITagService;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.Constant;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台机构处理
 * Created by yangchangyan on 2017/7/4.
 */
@Controller("com.yjd.back.contentmanager.OrganizationControl")
@Scope("prototype")
@RequestMapping("/org")
public class OrganizationControl extends BaseControl {
    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IIntroDetailService introDetailService;

    @Resource
    private ITagService tagService;

    @Resource
    private IFundChannelService fundChannelService;

    /**
     * 查询所有机构，分页查询
     * @return void
     * @throws
     */
    @RequestMapping(value = "/all")
    public String allOrganization() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", "create_time desc");
        paramMap.put("rows", "20");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.organizationService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/org/all"));

        OrganizationModel om = null;
        for(Object obj : pager.getPagerModel().getDataList()){
            om = (OrganizationModel) obj;
            om.getStrMap().put("address", CityUtil.getFullCityNames(om.getOrg_city(), "-")+" "+om.getOrg_address());
            om.getStrMap().put("create_time", DateUtil.timestampToDateString(om.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            om.getStrMap().put("last_update_time", DateUtil.timestampToDateString(om.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);

        return "allOrganization";
    }

    /**
     * 发布新机构编辑页面
     * @return void
     * @throws
     */
    @RequestMapping(value = "/add")
    public String addOrganizationPage() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        OrganizationModel org = new OrganizationModel();
        String period = SysParamUtil.getValue(Constant.SysParamKeyEnum.MFQ_PERIODS_CONFIG);
        org.setLimit_config(period);
        request.setAttribute("org", org);
        request.setAttribute("tagModelList", tagService.queryTags(null, ReferenceTypeEnum.ORGANIZATION));
        request.setAttribute("sheng_city", CityUtil.getChildCitysById(0));
        request.setAttribute("cityJson", FrameUtil.json(CityUtil.getCitys()));
        request.setAttribute("orgTypeList", this.orgType());
        request.setAttribute("serviceTypeList", TypeShowUtils.getServiceTypeMap());
        request.setAttribute("fundChannelList", allFundChannel());
        return "addOrganization";
    }

    /**
     * 编辑页面
     * @return void
     * @throws
     */
    @RequestMapping(value = "/edit")
    public String editOrganizationPage(Long id) throws Exception {
        OrganizationModel om = organizationService.getModelById(id, DbWREnums.READ);
        om.getStrMap();
        if(StringUtil.isNotEmpty(om.getOrg_pic())){
            om.getStrMap().put("org_pic", ServletUtil.getFileUrl(om.getOrg_pic()));
        }
        try {
            om.getStrMap().put("org_address", CityUtil.getFullCityNames(om.getOrg_city(), "-") + om.getOrg_address());
        } catch (Exception e) {
            om.getStrMap().put("org_address", om.getOrg_address());
        }
        IntroDetailModel idm = introDetailService.getModelById(om.getDetail_id(), DbWREnums.READ);
        if(null != idm){
            om.getStrMap().put("detail", idm.getContent());
        }
        request.setAttribute("tagModelList", tagService.queryTags(id, ReferenceTypeEnum.ORGANIZATION));
        request.setAttribute("org", om);
        request.setAttribute("sheng_city", CityUtil.getChildCitysById(0));
        request.setAttribute("cityJson", FrameUtil.json(CityUtil.getCitys()));
        request.setAttribute("orgTypeList", this.orgType());
        request.setAttribute("serviceTypeList", TypeShowUtils.getServiceTypeMap());
        request.setAttribute("fundChannelList", Collections.EMPTY_LIST);
        if(om.getFund_channel().intValue() > 0){
            request.setAttribute("fundChannelList", allFundChannel());
        }
        return "addOrganization";
    }

    /**
     * 发布新机构
     * @return void
     * @throws
     */
    @RequestMapping(value = "/add/submit")
    public void addOrganization(MultipartHttpServletRequest multipartRequest, OrganizationModel org) throws Exception {
        if(StringUtil.isEmpty(org.getOrg_name())){
            FrameUtil.throwBaseException1("机构名不能为空");
        }

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        // 获取用户选取的最小一级的城市id
        String org_city_id = (String)paramMap.get("l3");
        if(StringUtil.isEmpty(org_city_id)){
            org_city_id = (String)paramMap.get("l2");
        }
        if(StringUtil.isEmpty(org_city_id)){
            org_city_id = (String)paramMap.get("l1");
        }
        if(StringUtil.isNotEmpty(org_city_id)){
            org.setOrg_city(Long.valueOf(org_city_id));
        }

        // 上传机构图片
        ResourceModel res = new ResourceModel();
        res.setRef_type(ReferenceTypeEnum.ORGANIZATION.getCode());
        res.setRef_id(org.getOrg_id());
        String image_path = FileUtil.uploadFileToRemote(multipartRequest.getFileMap(), ReferenceTypeEnum.ORGANIZATION, res);
        if(StringUtil.isNotEmpty(image_path)){
            org.setOrg_pic(image_path);
        }

        organizationService.createOrUpdate(org, (String)paramMap.get("detail"), request.getParameterValues("tags"));

        this.successMsg(ServletUtil.getUrl("/org/all"), "保存机构成功");
    }

    @RequestMapping("/delete")
    public void deleteOrg(Long id) throws Exception {
        OrganizationModel org = organizationService.getModelById(id, DbWREnums.READ);
        if(null == org){
            this.errorMsg(ServletUtil.getUrl("/org/all"), "机构不存在");
        }
        introDetailService.delete(org.getDetail_id());
        organizationService.delete(id);
        this.successMsg(ServletUtil.getUrl("/org/all"), "操作成功！");
    }

    /**
     * 开启机构
     * @return void
     * @throws
     */
    @RequestMapping(value = "/open")
    public void openOrg(Long id) throws Exception {
        changeOrgIsUsed(id,1);
        this.successMsg("开启机构成功");
    }

    /**
     *禁用机构
     * @return void
     * @throws
     */
    @RequestMapping(value = "/close")
    public void closeOrg(Long id) throws Exception {
        changeOrgIsUsed(id,0);
        this.successMsg("禁用机构成功");
    }

    private void changeOrgIsUsed(Long id,Integer isUsed)throws Exception{
        if(id==null||isUsed==null){
            FrameUtil.throwBaseException1("参数不能为空");
        }
        OrganizationModel organizationModel = this.organizationService.getModelById(id, DbWREnums.READ);
        if(null == organizationModel){
            FrameUtil.throwBaseException1("机构不存在");
        }
        organizationService.updateMap(FrameUtil.newHashMap("org_id",id,"is_used",isUsed));
    }

    private Map<Integer, String> orgType() throws Exception {
        Map<Integer, String> orgType = new HashMap<Integer, String>();

        SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.ORGANIZATION_TYPE);
        if(null == sysParam){
            return orgType;
        }

        orgType = JSON.parseObject(sysParam.getParam_value(), new TypeReference<Map<Integer, String>>(){});

        return orgType;
    }

    private List<FundChannelDto> allFundChannel() throws Exception {
        List<FundChannelDto> chn = new ArrayList<>();
        List<FundChannelModel> channels = this.fundChannelService.queryAllFundChannel();
        for(FundChannelModel fm:channels){
            FundChannelDto dto = new FundChannelDto();
            BeanUtils.copyProperties(fm, dto);
            chn.add(dto);
        }
        return chn;
    }
}
